#include "Ethernet.h"
#include <QDebug>

/**
 * @brief 构造函数
 * @param parent 父对象指针
 */
Ethernet::Ethernet(QObject *parent) : CommunicationInterface(parent), m_tcpSocket(new QTcpSocket(this)) {
    m_currentStatus = "disconnected";
    connect(m_tcpSocket, &QTcpSocket::connected, this, [this]() {
        m_currentStatus = "connected";
        emit statusChanged(m_currentStatus);
    });
    connect(m_tcpSocket, &QTcpSocket::disconnected, this, [this]() {
        m_currentStatus = "disconnected";
        emit statusChanged(m_currentStatus);
    });
}

/**
 * @brief 初始化以太网连接
 * @param ipAddress 服务器IP地址（如"192.168.1.100"）
 * @param port 服务器端口号（默认8080）
 * @return 连接成功返回true，失败返回false
 */
bool Ethernet::initialize(const QVariantMap &params) {
        QString ipAddress = params.value("ipAddress").toString();
        int port = params.value("port").toInt();
    if (m_tcpSocket->state() == QTcpSocket::ConnectedState) return false;

    m_tcpSocket->connectToHost(ipAddress, port);
    if (m_tcpSocket->waitForConnected(3000)) {
        qDebug() << "Connected to " << ipAddress << ":" << port;
        return true;
    } else {
        m_currentStatus = "connect_failed";
        emit statusChanged(m_currentStatus);
        qWarning() << "Failed to connect to " << ipAddress << ":" << port << ": " << m_tcpSocket->errorString();
        return false;
    }
}

/**
 * @brief 反初始化并断开连接
 */
void Ethernet::uninitialize() {
    if (m_tcpSocket->state() == QTcpSocket::ConnectedState) {
        m_tcpSocket->disconnectFromHost();
        qDebug() << "Ethernet connection closed.";
    }
}

/**
 * @brief 发送数据到以太网服务器
 * @param data 待发送的字节数据
 * @return 发送成功返回true，失败返回false
 */
bool Ethernet::sendData(const QByteArray &data) {
    if (m_tcpSocket->state() != QTcpSocket::ConnectedState) {
        qWarning() << "Cannot send data: Ethernet not connected.";
        return false;
    }
    qint64 bytesWritten = m_tcpSocket->write(data);
    if (bytesWritten == data.size()) {
        qDebug() << "Sent " << bytesWritten << " bytes to Ethernet server.";
        return true;
    } else {
        qWarning() << "Failed to send data: " << m_tcpSocket->errorString();
        return false;
    }
}

/**
 * @brief 获取通信类型
 * @return 字符串"Ethernet"
 */
QString Ethernet::type() const {
    return "Ethernet";
}

/**
 * @brief 获取当前状态
 * @return 状态描述字符串（如"connected"/"disconnected"）
 */
QString Ethernet::status() const {
    return m_currentStatus;
}